package com.demo.uitls.aliyun.ipinfo.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.demo.uitls.aliyun.common.AbstractAliCallTemplate;
import com.demo.uitls.aliyun.common.Request;
import com.demo.uitls.aliyun.common.Response;
import com.demo.uitls.aliyun.common.constant.HttpHeader;
import com.demo.uitls.aliyun.common.enums.Method;
import com.demo.uitls.aliyun.ipinfo.IGetIpInfoStrategy;
import com.demo.uitls.aliyun.ipinfo.IpInfo;
import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author DongXL
 * @Create 2017-03-27 18:07
 */
public class AliGetIpInfoStrategyImpl extends AbstractAliCallTemplate implements IGetIpInfoStrategy {

    public static final AliGetIpInfoStrategyImpl INSTANCE = new AliGetIpInfoStrategyImpl();

    private final String HOST = "dm-81.data.aliyun.com";
    private final String PATH = "/rest/160601/ip/getIpInfo.json";
    private final String KEY_IP = "ip";

    @Override
    public IpInfo getIpInfo(String ip) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put(KEY_IP, ip);
        Response response = super.execute(params);
        String ret = response.getBody();
        if (StringUtils.isBlank(ret)) {
            return null;
        }
        JSONObject jsonObject = JSON.parseObject(ret);
        if (jsonObject == null) {
            return null;
        }
        return JSON.parseObject(jsonObject.getString("data"), IpInfo.class);
    }

    @Override
    public Method returnMethod() {
        return Method.GET;
    }

    @Override
    public String returnInterfaceHost() {
        return this.HOST;
    }

    @Override
    public String returnInterfacePath() {
        return this.PATH;
    }

    @Override
    public void wrapQuerys(Request request, Map<String, String> params) {
        request.setQuerys(params);
    }

    @Override
    public void wrapHeaders(Request request, Map<String, String> params) {
        Map<String, String> headers = new HashMap<>();
        headers.put(HttpHeader.HTTP_HEADER_ACCEPT, "application/json");
        headers.put(HttpHeader.HTTP_HEADER_AUTHORIZATION, getAppCode());
        request.setHeaders(headers);
    }

    @Override
    public void wrapBody(Request request, Map<String, String> params) {

    }

}
